<script setup lang="ts">
import {
  getDepositoryByStoreId,
  getGoodsBystore
} from "@/api/orderManag/crossStore";
import { ImageViewer } from "@/components/common/ImageViewer";
import { dealDataAdd, dealDataExcept, dealDataRide } from "@/utils/common";
import { cloneDeep } from "@pureadmin/utils";
import { computed, onMounted, reactive, ref, watch } from "vue";
import { formRules } from "../utils/rule";
import { FormProps } from "../utils/types";
import { useShipperAdd } from "./columns";

import Delete from "@iconify-icons/ep/delete";
// 获取商品列表

const props = withDefaults(defineProps<FormProps>(), {
  formInline: () => ({
    id: "",
    buyStoreId: undefined,
    depositoryId: undefined,
    depositoryName: undefined,
    addItemList: undefined,
    updateItemList: undefined,
    deleteOrderItemIds: undefined,
    fareType: 1, // 运费类型 1包邮 2提前支付 3到付
    fare: undefined,
    orderNum: undefined,
    orderPrice: undefined,
    des: "",
    dataList: []
  }),
  storeList: null
});

const ruleFormRef = ref();
const loadingDetail = ref(false);
const newFormInline = ref(props.formInline);

//  左边供应商商品列表
const depositoryList = ref([]);
let goodsList = ref([]);
// goodsList.value = [
//   {
//     id: 1,
//     goodsId: 1,
//     logo: "https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg",
//     goodsName: "商品名称商品名称1",
//     goodsType: 1,
//     canUseNum: 200,
//     goodsCode: "bm001",
//     avgBuyPrice: 2800,
//     specCodeList: [
//       {
//         id: 1,
//         specName: "蓝",
//         specCode: "spec001",
//         canUseNum: 10,
//         avgBuyPrice: 2800
//       },
//       { id: 2, specName: "红", specCode: "spec002", canUseNum: 20 },
//       { id: 3, specName: "黄", specCode: "spec003", canUseNum: 30 }
//     ],
//     checkTagsID: [],
//     price: 28,
//     spdj: undefined,
//     spsl: undefined,
//     xj: "",
//     fthdj: "",
//     fthzj: ""
//   }
// ];

let checkGoodsID = reactive([]);
function chooseGood(item) {
  // 左边商品选中或取消
  const index = checkGoodsID.indexOf(item.goodsId);
  if (index != -1) {
    // 移除
    checkGoodsID.splice(index, 1);
    let findIndex = newFormInline.value.dataList.findIndex(
      v => v.goodsId == item.goodsId
    );
    if (findIndex != -1) {
      newFormInline.value.dataList.splice(findIndex, 1);
    }
  } else {
    // 新增
    checkGoodsID.push(item.goodsId);
    if (item.specCodeList.length == 0 || item.specCodeList.length == 1) {
      // 如果没有商品规格，则直接添加数据
      item.spgg = "--";
      item.spdj = dealDataExcept(item.specCodeList[0]?.buyPrice);
      item.spsl = item.orderMin;
      item.xj = undefined;
      item.ftje = undefined;
      item.fthdj = undefined;
      item.fthzj = undefined;
      item.specImageJson = item.specImageJson || item.imageJson;
      item.specCode = item.specCodeList[0]?.specCode;
      item.specName = item.specCodeList[0]?.specName;
      item.barCode = item.specCodeList[0]?.barCode;
      item.goodsId = item.goodsId;
      let row = item;
      newFormInline.value.dataList.push(row);
    }
  }
}

function checkTags(item, tag) {
  // 多规格商品根据规格添加数据，有多个规格可以添加多个数据
  // 左边商品规格选中或取消
  const index = item.checkTagsID.indexOf(tag.specName);
  if (index == -1) {
    item.checkTagsID.push(tag.specName);
    item.spgg = tag.specName;
    item.spdj = dealDataExcept(tag.avgBuyPrice);
    item.spsl = item.orderMin;
    item.specCode = tag.specCode;
    item.specImageJson = tag.specImageJson || item.imageJson;
    item.specName = tag.specName;
    item.barCode = tag.barCode;
    let row = cloneDeep(item);
    newFormInline.value.dataList.push(row);
  } else {
    item.checkTagsID.splice(index, 1);
    newFormInline.value.dataList.splice(index, 1);
  }
}

function getRef() {
  return ruleFormRef.value;
}

const searchValue = ref("");
const dataLoading = ref(false);

const pagination = reactive({ current: 1, pageSize: 18, total: 0 });
const onPageSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.current = 1;
  loadGoodsList();
};
const onCurrentChange = (current: number) => {
  pagination.current = current;
  loadGoodsList();
};

const { columns } = useShipperAdd();

// 右边删除按钮
function onDel(row) {
  // 编辑删除 deleteOrderItemIds  订单删除的商品id数组
  if (row.type == "edit") {
    // 编辑删除 商品id数组
    newFormInline.value.deleteOrderItemIds.push(row.id);
  }
  console.log(newFormInline.value.deleteOrderItemIds);

  if (row.spgg == "--") {
    // 没有商品规格的删除

    const index = checkGoodsID.indexOf(row.id);
    checkGoodsID.splice(index, 1);

    const i = newFormInline.value.dataList.indexOf(row);
    newFormInline.value.dataList.splice(i, 1);
  } else {
    // 多规格商品的删除

    row.specCodeList?.forEach(v => {
      if (row.spgg == v.specName) {
        const index = newFormInline.value.dataList.indexOf(row);
        newFormInline.value.dataList.splice(index, 1);

        // 根据右边数据的商品规格，取消左边多规格的选中状态
        goodsList.value.forEach((item, i) => {
          if (item.id == row.id) {
            const index = goodsList.value[i].checkTagsID.indexOf(row.spgg);
            goodsList.value[i].checkTagsID.splice(index, 1);
          }
        });
      }
    });
  }
}

watch(
  () => newFormInline.value.dataList,
  val => {
    // 计算订单数量
    newFormInline.value.orderNum = val.length;

    // 计算分摊后单价 分摊后总价
    let fareType = newFormInline.value.fareType;
    val?.forEach(item => {
      if (item.spdj >= 0 && item.spdj && item.spsl >= 0 && item.spsl) {
        item.xj = dealDataRide(item.spdj, item.spsl);
        /**
         * 如果已经填过运费金额，再次修改商品单价 或者 商品数量
         * 重新计算分摊后单价，分摊后总价
         */
        if (
          fareType == 2 &&
          newFormInline.value.fare &&
          newFormInline.value.fare > 0
        ) {
          item.ftje = dealDataRide(
            dealDataExcept(item.xj, totalPrice.value, 2),
            newFormInline.value.fare,
            2
          );
          item.fthdj = dealDataAdd(
            dealDataExcept(item.ftje, item.spsl, 2),
            item.spdj
          );
          item.fthzj = dealDataRide(item.fthdj, item.spsl);
        } else {
          item.ftje = undefined;
          item.fthdj = undefined;
          item.fthzj = undefined;
        }
      }
    });
  },
  { deep: true }
);

const totalPrice = computed(() => {
  let money = newFormInline.value.dataList.reduce((prev, current) => {
    let cur = isNaN(current.xj) ? 0 : current.xj;
    return dealDataAdd(cur, prev);
  }, 0);
  return money;
});

watch(
  () => totalPrice.value,
  val => {
    // 计算订单总价
    newFormInline.value.orderPrice = dealDataAdd(val, newFormInline.value.fare);
  },
  { deep: true }
);

function changeRadio(val) {
  if (val != 2) {
    newFormInline.value.fare = undefined;
  }
}

/**
 * A商品分摊金额 = A商品总价 / 备货订单总金额 * 备货运费，
 * A商品分摊后单价 = A商品分摊金额 / A商品备货数量 + A商品备货单价
 */
watch(
  () => newFormInline.value.fare,
  val => {
    if (newFormInline.value.dataList.length > 0) {
      let fareType = newFormInline.value.fareType;
      newFormInline.value.dataList.forEach(item => {
        // 如果分摊金额为0 则分摊单价和分摊金额都为空
        if (fareType != 2 || val == 0) {
          item.ftje = undefined;
          item.fthdj = undefined;
          item.fthzj = undefined;
          return;
        }

        // 如果商品小计为空 则跳过
        if (!item.xj) return;
        // 计算分摊后单价 分摊后总价
        item.ftje = dealDataRide(
          dealDataExcept(item.xj, totalPrice.value, 2),
          newFormInline.value.fare,
          2
        );
        item.fthdj = dealDataAdd(
          dealDataExcept(item.ftje, item.spsl, 2),
          item.spdj
        );
        item.fthzj = dealDataRide(item.fthdj, item.spsl);
      });
    }

    // 计算订单总价
    newFormInline.value.orderPrice = dealDataAdd(totalPrice.value, val);
  },
  { deep: true }
);

// 供应商
const storeChange = () => {
  // 获取仓库
  newFormInline.value.depositoryId = undefined;
  loadDepositoryList();

  pagination.current = 1;
  pagination.pageSize = 18;
  pagination.total = 0;
  checkGoodsID = [];
  newFormInline.value.dataList = [];
  loadGoodsList();
};

const depositoryChange = () => {
  let depositoryName = "";
  if (newFormInline.value.depositoryId) {
    depositoryName = depositoryList.value.find(
      v => v.id == newFormInline.value.depositoryId
    ).depositoryName;
  }
  newFormInline.value.depositoryName = depositoryName;
};

// 选择供应商获取对应的商品列表
async function loadGoodsList() {
  if (!newFormInline.value.buyStoreId) {
    goodsList.value = [];
    return;
  }

  dataLoading.value = true;
  const params: any = {
    buyStoreId: newFormInline.value.buyStoreId,
    pageNum: pagination.current,
    pageSize: pagination.pageSize
  };
  if (searchValue.value) {
    params.search = searchValue.value;
  }
  const { data } = await getGoodsBystore(params).catch(() => {
    dataLoading.value = false;
  });
  data.records.forEach(item => {
    item.type = "add";
    item.checkTagsID = [];
  });
  goodsList.value = data.records || [];
  pagination.total = data.total;
  pagination.pageSize = data.pageSize;
  pagination.current = data.pageNum;
  dataLoading.value = false;
}

// 获取仓库
const loadDepositoryList = () => {
  if (!newFormInline.value.buyStoreId) {
    depositoryList.value = [];
    return;
  }

  let params = {
    storeId: newFormInline.value.buyStoreId
  };
  getDepositoryByStoreId(params).then(res => {
    depositoryList.value = res.data || [];
  });
};

// 获取详情
async function loadGoodsDetail(id) {
  loadingDetail.value = true;
  // let { data } = await purchaseDetail(id);
  let data: any = {};
  let newDatas = data.itemList;
  // 处理返回的值显示  商品名称 商品规格  商品单价 商品数量 小计 分摊金额 分摊后单价 分摊后总价
  newDatas.forEach(item => {
    item.type = "edit";

    // 如果有规格图片 则显示规格图片
    if (item.specImageJson) {
      item.imageJson = item.specImageJson;
    }

    // 如果没有规格名称表示是单规格 则显示--
    if (item.specName) {
      item.spgg = item.specName;
    } else {
      item.spgg = "--";
    }

    // 商品单价
    item.spdj = dealDataExcept(item.avgBuyPrice);

    // 商品数量
    item.spsl = item.amount;

    item.specCodeList = newDatas;
  });
  console.log("log", newDatas);
  newFormInline.value.dataList = newDatas;

  // 运费金额
  let fare = undefined;
  if (data.fare && data.fareType == 2) {
    fare = dealDataExcept(data.fare);
  }
  newFormInline.value.fare = fare;
  loadingDetail.value = false;
}

onMounted(async () => {
  if (newFormInline.value.id) {
    loadGoodsDetail(newFormInline.value.id);
    loadGoodsList();
  }
});

defineExpose({ getRef });
</script>

<template>
  <el-form
    ref="ruleFormRef"
    :rules="formRules"
    :model="newFormInline"
    label-width="110px"
  >
    <div class="flex">
      <el-form-item label="选择购买门店" prop="buyStoreId">
        <el-select
          v-model="newFormInline.buyStoreId"
          filterable
          placeholder="请选择"
          clearable
          class="!w-[300px]"
          :disabled="newFormInline.id ? true : false"
          @change="storeChange"
        >
          <el-option
            v-for="item in storeList"
            :key="item.id"
            :label="item.storeName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="选择仓库" prop="depositoryId" class="ml-5">
        <el-select
          v-model="newFormInline.depositoryId"
          filterable
          placeholder="请选择"
          clearable
          :disabled="newFormInline.id ? true : false"
          class="!w-[280px]"
          @change="depositoryChange"
        >
          <el-option
            v-for="item in depositoryList"
            :key="item.id"
            :label="item.depositoryName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </div>
    <!-- 商品列表 -->
    <div class="goods-box">
      <div class="g-left">
        <div class="search">
          <el-input
            v-model="searchValue"
            class="!w-[300px]"
            placeholder="输入商品编码/名称后回车选中"
            clearable
            @change="loadGoodsList"
          >
            <template #suffix>
              <el-icon class="el-input__icon">
                <IconifyIconOffline
                  v-show="searchValue.length === 0"
                  icon="ri:search-line"
                />
              </el-icon>
            </template>
          </el-input>
        </div>
        <div v-loading="dataLoading" class="content">
          <ul v-if="goodsList.length > 0" class="goods-items">
            <div v-for="(item, i) in goodsList" :key="i" class="goods-pitem">
              <li
                :class="
                  ((item.specCodeList?.length == 0 ||
                    item.specCodeList?.length == 1) &&
                    checkGoodsID.includes(item.goodsId)) ||
                  (item.specCodeList?.length > 1 && item.checkTagsID.length > 0)
                    ? 'active'
                    : ''
                "
                class="goods-item"
                @click="chooseGood(item)"
              >
                <ImageViewer
                  :src="item.imageJson"
                  radius="8px"
                  width="75px"
                  height="75px"
                  class="mr-2"
                />
                <div class="item-rig">
                  <div class="top">
                    <div class="name truncate">
                      <el-tooltip
                        :content="item.goodsName"
                        placement="top-start"
                      >
                        {{ item.goodsName }}
                      </el-tooltip>
                    </div>
                    <div
                      v-if="item.specCodeList && item.specCodeList.length > 0"
                      class="price"
                    >
                      ￥<span>{{
                        dealDataExcept(item.specCodeList[0]?.avgBuyPrice)
                      }}</span>
                    </div>
                  </div>

                  <!-- 规格列表 -->
                  <div v-if="item.specCodeList?.length > 1" class="spec-boxs">
                    <span
                      v-for="(tag, j) in item.specCodeList"
                      :key="j"
                      :class="
                        item.checkTagsID.includes(tag.specName) ? 'active' : ''
                      "
                      class="spec-item"
                      @click.stop="checkTags(item, tag)"
                    >
                      <el-tooltip placement="top-start">
                        <template #content>
                          <div>
                            {{ tag.specName }}
                            (￥{{ dealDataExcept(tag.avgBuyPrice) }} )
                          </div>
                        </template>
                        <span class="truncate block">
                          {{ tag.specName }}
                        </span>
                      </el-tooltip>
                    </span>
                  </div>

                  <!-- 库存 -->
                  <div class="mt-[7px] text-xs">
                    库存: {{ item.canUseNum || 0 }}
                  </div>
                </div>
              </li>
            </div>
          </ul>
          <el-empty v-else description="暂无数据" />
        </div>
        <div class="footer">
          <el-pagination
            v-model:currentPage="pagination.current"
            :page-size="pagination.pageSize"
            :total="pagination.total"
            :page-sizes="[18, 36, 48]"
            :background="true"
            layout="total,sizes, prev, pager, next, jumper"
            @size-change="onPageSizeChange"
            @current-change="onCurrentChange"
          />
        </div>
      </div>
      <div class="g-right">
        <h3 class="text-[#29281C] p-3">商品选择</h3>
        <pure-table
          class="!w-full"
          align-whole="center"
          showOverflowTooltip
          row-key="id"
          :data="newFormInline.dataList"
          :columns="columns"
          height="calc(100vh - 450px)"
          :header-cell-style="{
            background: 'var(--el-fill-color-light)',
            color: 'var(--el-text-color-primary)'
          }"
        >
          <template #operation="{ row }">
            <div class="flex justify-center">
              <iconifyIconOffline
                class="text-red-500 text-lg cursor-pointer"
                :icon="Delete"
                @click="onDel(row)"
              />
            </div>
          </template>
        </pure-table>
        <div class="fare-form">
          <el-form-item label="备注" prop="des">
            <el-input
              v-model="newFormInline.des"
              clearable
              :rows="4"
              class="!w-[350px]"
              placeholder="请输入"
              type="textarea"
            />
          </el-form-item>
        </div>

        <div class="goods-total">
          <div class="lef flex items-center text-sm text-[#29281C]">
            共
            <span class="text-[#F76847] mx-0.5">
              {{ newFormInline.dataList.length }}
            </span>
            件商品
          </div>
          <div class="text-lg text-[#F76847] min-w-[110px]">
            合计：
            <span v-if="newFormInline.dataList.length > 0"
              >¥
              {{
                dealDataAdd(totalPrice, newFormInline.fare || 0) || "--"
              }}</span
            >
            <span v-else>--</span>
          </div>
        </div>
      </div>
    </div>
  </el-form>
</template>
<style lang="scss" scoped>
.goods-box {
  width: 100%;
  display: flex;
  justify-content: space-between;
  height: calc(100vh - 235px);
  .g-left,
  .g-right {
    position: relative;
    border-radius: 12px;
    border: 1px solid #e5e5da;
    overflow: hidden;
  }
  .g-left {
    width: 60%;
    display: flex;
    flex-direction: column;
    margin-right: 12px;
    .search {
      padding: 12px 12px;
      border-bottom: 1px solid #efefef;
    }
  }
  .g-right {
    min-width: 615px;
    width: 40%;
    display: flex;
    flex-direction: column;
    .fare-form {
      flex: 1;
      padding-top: 15px;
    }
    .goods-total {
      width: 100%;
      padding: 5px 16px;
      border-top: 1px solid #f2f2eb;
      display: flex;
      justify-content: space-between;
    }
  }
  .content {
    flex: 1;
    padding: 6px;
    overflow: auto;
  }
  .goods-items {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    box-sizing: border-box;
    .goods-pitem {
      width: 33.333%;
    }
    .goods-item {
      padding: 6px;
      margin: 6px;
      background: #ffffff;
      box-shadow: 0px 0px 6px 0px rgba(0, 0, 0, 0.12);
      border-radius: 8px 8px 8px 8px;
      border: 2px solid transparent;
      min-height: 75px;
      display: flex;
      justify-content: space-between;
      cursor: pointer;
      box-sizing: border-box;
      .item-rig {
        flex: 1;
        overflow: hidden;
        position: relative;
        .top {
          display: flex;
          margin-bottom: 5px;
          .name {
            flex: 1;
            font-size: 14px;
            font-weight: bold;
            color: #29281c;
          }
        }
        .price {
          font-weight: normal;
          font-size: 14px;
          color: #f76847;
          span {
            font-size: 15px;
            font-weight: bold;
          }
        }
        .spec-boxs {
          display: flex;
          flex-wrap: wrap;
          gap: 5px;
          .spec-item {
            font-size: 12px;
            padding: 2px 5px;
            color: #6296ff;
            max-width: 70px;
            border: 1px solid #6296ff;
            border-radius: 5px;
            &.active {
              color: #fff;
              background: #6296ff;
            }
          }
        }
      }
      &.active {
        border: 2px solid #6296ff;
      }
    }
    .goods-item:hover {
      border: 2px solid #6296ff;
    }
  }
  .footer {
    padding: 12px;
    display: flex;
    justify-content: flex-end;
    border-top: 1px solid #efefef;
  }
}

.truncates {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
}

@media (max-width: 1350px) {
  .goods-box .goods-items .goods-pitem {
    width: 50%;
  }
}
</style>
